<?php

namespace app\model;

use think\Model;
use think\facade\Db;

/**
 * 盲盒模型类（后台管理）
 * Class BlindBoxModel
 * @package app\model
 */
class BlindBoxModel extends Model
{
    protected $pk = 'id';
    protected $table = 'sh_blind_box';

    /**
     * 获取盲盒列表（后台管理）
     * @param array $filter 筛选条件
     * @return array
     */
    public static function get_list($filter = [])
    {
        $uniacid = current_uni_account();
        $where = ' bb.uniacid = ' . $uniacid;
        
        // 默认只查询未删除的盲盒
        $where .= " AND bb.is_deleted = 0";
        
        if (!empty($filter['name'])) {
            $where .= " AND bb.name LIKE '%" . $filter['name'] . "%'";
        }
        
        if (isset($filter['status'])) {
            $where .= " AND bb.status = " . intval($filter['status']);
        }
        
        $sql = 'SELECT bb.*, 
                COUNT(bbp.id) as prize_count,
                SUM(CASE WHEN bbp.status = 1 THEN 1 ELSE 0 END) as active_prize_count
                FROM sh_blind_box bb
                LEFT JOIN sh_blind_box_prize bbp ON bb.id = bbp.blind_box_id
                WHERE ' . $where . '
                GROUP BY bb.id
                ORDER BY bb.sort_order ASC, bb.id DESC';
        
        return Db::query($sql);
    }

    /**
     * 获取盲盒详情（后台管理）
     * @param int $blind_box_id 盲盒ID
     * @return array|null
     */
    public static function detail($blind_box_id)
    {
        $sql = "SELECT bb.* 
                FROM sh_blind_box bb
                WHERE bb.id = " . intval($blind_box_id) . " 
                AND bb.is_deleted = 0";
        
        $result = Db::query($sql);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 创建或编辑盲盒
     * @param int $blind_box_id 盲盒ID，为0时表示新建
     * @param array $data 盲盒数据
     * @return int 盲盒ID
     */
    public static function edit($blind_box_id, $data)
    {
        $uniacid = current_uni_account();
        $time = date('Y-m-d H:i:s');
        
        if (!empty($blind_box_id)) {
            // 更新盲盒
            $sql = "UPDATE sh_blind_box SET
                    name = '" . addslashes($data['name']) . "',
                    description = '" . addslashes($data['description']) . "',
                    image = '" . addslashes($data['image']) . "',
                    price = " . floatval($data['price']) . ",
                    stock = " . intval($data['stock']) . ",
                    limit_per_user = " . intval($data['limit_per_user']) . ",
                    start_time = " . (!empty($data['start_time']) ? "'" . $data['start_time'] . "'" : "NULL") . ",
                    end_time = " . (!empty($data['end_time']) ? "'" . $data['end_time'] . "'" : "NULL") . ",
                    status = " . intval($data['status']) . ",
                    sort_order = " . intval($data['sort_order']) . ",
                    update_time = '" . $time . "'
                    WHERE id = " . intval($blind_box_id);
        } else {
            // 新建盲盒
            $sql = "INSERT INTO sh_blind_box SET
                    uniacid = " . $uniacid . ",
                    name = '" . addslashes($data['name']) . "',
                    description = '" . addslashes($data['description']) . "',
                    image = '" . addslashes($data['image']) . "',
                    price = " . floatval($data['price']) . ",
                    stock = " . intval($data['stock']) . ",
                    limit_per_user = " . intval($data['limit_per_user']) . ",
                    start_time = " . (!empty($data['start_time']) ? "'" . $data['start_time'] . "'" : "NULL") . ",
                    end_time = " . (!empty($data['end_time']) ? "'" . $data['end_time'] . "'" : "NULL") . ",
                    status = " . intval($data['status']) . ",
                    sort_order = " . intval($data['sort_order']) . ",
                    create_time = '" . $time . "',
                    update_time = '" . $time . "'";
        }
        
        Db::execute($sql);
        
        if (empty($blind_box_id)) {
            $blind_box_id = Db::name('sh_blind_box')->getLastInsID();
        }
        
        return $blind_box_id;
    }

    /**
     * 逻辑删除盲盒
     * @param mixed $ids 盲盒ID或ID数组
     * @return int 影响的行数
     */
    public static function remove($ids)
    {
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        $sql = 'UPDATE sh_blind_box SET is_deleted = 1 WHERE id IN(' . $ids . ')';
        
        return Db::execute($sql);
    }

    /**
     * 恢复已删除的盲盒
     * @param mixed $ids 盲盒ID或ID数组
     * @return int 影响的行数
     */
    public static function restore($ids)
    {
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        $sql = 'UPDATE sh_blind_box SET is_deleted = 0 WHERE id IN(' . $ids . ')';
        
        return Db::execute($sql);
    }

    /**
     * 更新盲盒状态
     * @param mixed $ids 盲盒ID或ID数组
     * @param int $status 状态
     * @return int 影响的行数
     */
    public static function updateStatus($ids, $status)
    {
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        $status = intval($status);
        
        $sql = 'UPDATE sh_blind_box SET status = ' . $status . ' WHERE id IN(' . $ids . ') AND is_deleted = 0';
        
        return Db::execute($sql);
    }

    /**
     * 获取盲盒奖品列表
     * @param int $blind_box_id 盲盒ID
     * @return array
     */
    public static function get_prizes($blind_box_id)
    {
        $sql = "SELECT bbp.*, g.image as goods_image, g.price as goods_price
                FROM sh_blind_box_prize bbp
                LEFT JOIN sh_goods g ON bbp.prize_type = 'goods' AND bbp.prize_id = g.id
                WHERE bbp.blind_box_id = " . intval($blind_box_id) . "
                ORDER BY bbp.sort_order ASC, bbp.id ASC";
        
        return Db::query($sql);
    }

    /**
     * 保存盲盒奖品
     * @param int $blind_box_id 盲盒ID
     * @param array $prizes 奖品数据数组
     * @return bool
     */
    public static function save_prizes($blind_box_id, $prizes)
    {
        // 删除旧的奖品配置
        $delete_sql = "DELETE FROM sh_blind_box_prize WHERE blind_box_id = " . intval($blind_box_id);
        Db::execute($delete_sql);
        
        if (empty($prizes)) {
            return true;
        }
        
        $values = [];
        $time = date('Y-m-d H:i:s');
        
        foreach ($prizes as $prize) {
            $total_stock = intval($prize['total_stock']);
            $remain_stock = isset($prize['remain_stock']) ? intval($prize['remain_stock']) : $total_stock;
            
            $values[] = "(" . intval($blind_box_id) . ", 
                        '" . addslashes($prize['prize_type']) . "', 
                        " . intval($prize['prize_id']) . ", 
                        '" . addslashes($prize['prize_name']) . "', 
                        '" . addslashes($prize['prize_image']) . "', 
                        '" . addslashes($prize['prize_value']) . "', 
                        " . floatval($prize['probability']) . ", 
                        " . $total_stock . ", 
                        " . $remain_stock . ", 
                        '" . addslashes($prize['prize_level']) . "', 
                        " . intval($prize['sort_order']) . ", 
                        " . intval($prize['status']) . ", 
                        '" . $time . "')";
        }
        
        $sql = "INSERT INTO sh_blind_box_prize 
                (blind_box_id, prize_type, prize_id, prize_name, prize_image, prize_value, 
                 probability, total_stock, remain_stock, prize_level, sort_order, status, create_time) 
                VALUES " . implode(',', $values);
        
        return Db::execute($sql);
    }

    /**
     * 获取所有抽奖记录总数（后台管理用）
     * @param array $filter 筛选条件
     * @return int
     */
    public static function get_all_records_count($filter = [])
    {
        $uniacid = current_uni_account();
        $where = " bbr.uniacid = " . $uniacid;
        
        if (!empty($filter['blind_box_id'])) {
            $where .= " AND bbr.blind_box_id = " . intval($filter['blind_box_id']);
        }
        
        if (!empty($filter['blind_box_name'])) {
            $where .= " AND bb.name LIKE '%" . addslashes($filter['blind_box_name']) . "%'";
        }
        
        if (!empty($filter['customer_name'])) {
            $where .= " AND c.name LIKE '%" . addslashes($filter['customer_name']) . "%'";
        }
        
        $sql = "SELECT COUNT(*) as count
                FROM sh_blind_box_record bbr
                LEFT JOIN sh_customer c ON bbr.customer_id = c.id
                LEFT JOIN sh_blind_box bb ON bbr.blind_box_id = bb.id
                WHERE " . $where;
        
        $result = Db::query($sql);
        return !empty($result) ? $result[0]['count'] : 0;
    }

    /**
     * 获取所有抽奖记录（后台管理用）
     * @param array $filter 筛选条件
     * @param int $offset 偏移量
     * @param int $limit 限制数量
     * @return array
     */
    public static function get_all_records($filter = [], $offset = 0, $limit = 15)
    {
        $uniacid = current_uni_account();
        $where = " bbr.uniacid = " . $uniacid;
        
        if (!empty($filter['blind_box_id'])) {
            $where .= " AND bbr.blind_box_id = " . intval($filter['blind_box_id']);
        }
        
        if (!empty($filter['blind_box_name'])) {
            $where .= " AND bb.name LIKE '%" . addslashes($filter['blind_box_name']) . "%'";
        }
        
        if (!empty($filter['customer_name'])) {
            $where .= " AND c.name LIKE '%" . addslashes($filter['customer_name']) . "%'";
        }
        
        $sql = "SELECT bbr.*, c.name as customer_name, c.telephone, bb.name as blind_box_name
                FROM sh_blind_box_record bbr
                LEFT JOIN sh_customer c ON bbr.customer_id = c.id
                LEFT JOIN sh_blind_box bb ON bbr.blind_box_id = bb.id
                WHERE " . $where . "
                ORDER BY bbr.create_time DESC
                LIMIT " . $offset . "," . $limit;
        
        return Db::query($sql);
    }

    /**
     * 发放奖品
     * @param int $record_id 记录ID
     * @param string $remark 备注
     * @return int
     */
    public static function deliver_prize($record_id, $remark = '')
    {
        $time = date('Y-m-d H:i:s');
        $sql = "UPDATE sh_blind_box_record SET
                is_delivered = 1,
                delivered_time = '" . $time . "',
                remark = '" . addslashes($remark) . "'
                WHERE id = " . intval($record_id);
        
        return Db::execute($sql);
    }

    /**
     * 获取盲盒订单详情（后台管理）
     * @param int $order_id 订单ID
     * @return array|null
     */
    public static function get_order_detail($order_id)
    {
        $uniacid = current_uni_account();
        
        // 查询订单基本信息
        $sql = "SELECT 
                    o.*,
                    c.name as customer_name,
                    c.telephone as customer_phone,
                    c.avatar as customer_avatar,
                    obb.blind_box_id,
                    obb.quantity as blind_box_quantity,
                    obb.is_drawn,
                    obb.draw_time,
                    bb.name as blind_box_name,
                    bb.image as blind_box_image,
                    bb.price as blind_box_price
                FROM sh_order o
                LEFT JOIN sh_customer c ON o.customer_id = c.id
                LEFT JOIN sh_order_blind_box obb ON o.id = obb.order_id
                LEFT JOIN sh_blind_box bb ON obb.blind_box_id = bb.id
                WHERE o.id = " . intval($order_id) . "
                AND o.uniacid = " . $uniacid;
        
        $result = Db::query($sql);
        
        if (empty($result)) {
            return null;
        }
        
        $order = $result[0];
        
        // 查询订单商品
        $goods_sql = "SELECT * FROM sh_order_goods WHERE order_id = " . intval($order_id);
        $order['goods'] = Db::query($goods_sql);
        
        // 查询订单总计
        $total_sql = "SELECT * FROM sh_order_total WHERE order_id = " . intval($order_id);
        $totals = Db::query($total_sql);
        $order['total_items'] = [];
        foreach ($totals as $total) {
            $order['total_items'][$total['code']] = [
                'name' => $total['code'],
                'value' => $total['value']
            ];
        }
        
        // 查询自提信息（如果有）
        if ($order['shipping_method'] == 'pickup') {
            $pickup_sql = "SELECT * FROM sh_order_pickup WHERE order_id = " . intval($order_id);
            $pickup_result = Db::query($pickup_sql);
            $order['pickup_info'] = !empty($pickup_result) ? $pickup_result[0] : null;
        }
        
        // 查询抽奖记录
        if ($order['is_drawn'] == 1) {
            $record_sql = "SELECT bbr.*
                          FROM sh_blind_box_record bbr
                          WHERE bbr.order_id = " . intval($order_id) . "
                          AND bbr.uniacid = " . $uniacid . "
                          ORDER BY bbr.create_time ASC";
            $order['draw_records'] = Db::query($record_sql);
        } else {
            $order['draw_records'] = [];
        }
        
        return $order;
    }
}
